<template>
    <div class="course-box">
        <div class="course-head">
            <div class="head-title">课程列表</div>
            <div class="course">
                <el-button v-if="courseId.length > 0" type="danger" plain @click="deleteCourses(courseId)"
                    class="head-btn"><i class=" iconfont icon-shanchu"></i>批量删除</el-button>
                <el-button class="head-btn" type="primary" plain @click="addCourseBtn"><i
                        class=" iconfont icon-tianjia"></i>
                    新增课程</el-button>
                <div class="option">
                    <el-input v-model="search" placeholder="请输入课程名称" class="input">
                        <template #append>
                            <el-button class="iconfont icon-sousuo3" @click="searchByTitel"></el-button>
                        </template>
                    </el-input>
                </div>
            </div>
        </div>
        <div class="table">
            <el-table :data="tableData" style="width: 100wh" @selection-change="selectCourseId"
                :header-cell-style="{ 'text-align': 'center', background: '#f0f4f7', color: '#606266' }"
                max-height="450" :row-style="{ height: '5vh' }">
                <el-table-column type="selection" width="35" align="center" />
                <el-table-column label="序号" type="index" width="80" align="center" />
                <el-table-column prop="courseName" label="课程名" max-width="180" min-width="100px" align="center"
                    :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column prop="description" label="课程描述" max-width="100" align="center"
                    :show-overflow-tooltip="true" />
                <el-table-column prop="creator" label="创建人" max-width="100" align="center" />
                <el-table-column prop="createTime" label="创建时间" max-width="150" min-width="100px" align="center" />
                <el-table-column label="操作" align="center" min-width="90px">
                    <template #default="scope">
                        <el-button type="primary" circle class="iconfont icon-bianji"
                            @click="updateCourseBtn(scope.row)" />
                        <el-popconfirm width="120" confirm-button-text="确认" cancel-button-text="取消"
                            @confirm="deleteCourse(scope.row)" title="确认删除?">
                            <template #reference>
                                <el-button type="danger" circle class="iconfont icon-shanchu" />
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="foot">
            <div class="question-foot">
                <el-pagination v-model:current-page="paginationData.pageNum" v-model:page-size="paginationData.pageSize"
                    :page-sizes="[20, 50, 100]" :small="paginationData.small" layout="sizes, prev, pager, next"
                    :total="Number(paginationData.total)" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" class="pagination" />
            </div>
        </div>
        <el-dialog v-model="visibleDialog" width="40%" draggable class="dialog">
            <template #header class="dialog-header">
                <div v-if="dialogHeader == 1">新增课程</div>
                <div v-if="dialogHeader == 2">更新课程</div>

            </template>
            <el-form label-position="left" style="max-width: 400px" :model="courseData" label-width="auto"
                class="dialog-form">
                <el-form-item label="课程名称">
                    <el-input v-model="courseData.courseName" placeholder="请输入课程名" class="dialog-input" />
                </el-form-item>
                <el-form-item label="课程描述">
                    <el-input v-model="courseData.description" placeholder="请输入课程描述" class="dialog-input" />
                </el-form-item>
                <el-form-item label="所属部门">
                    <el-cascader :options="deptOptions" v-model="courseData.belongDeptId" placeholder="请选择所属部门"
                        :props="{ checkStrictly: true }" ref="cascaderRef" :show-all-levels="false" filterable
                        class="cascader" />
                </el-form-item>
                <el-form-item label="课程图片">
                    <el-upload :http-request="httpRequest" multiple :show-file-list="true" list-type="picture-card"
                        :class="{ disabled: uploadDisabled }"><el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <!-- <el-form-item label="教师id">
                    <el-input v-model="courseData.teacherId" placeholder="请输入描述" />
                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" v-if="dialogHeader == 1" @click="addCourse(courseData)"
                        class="dialog-btn">确定</el-button>
                    <el-button type="primary" @click="updateCourse(courseData)" class="dialog-btn"
                        v-if="dialogHeader == 2">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getCourseListAPI, findNodesAPI, addCourseAPI, updateCourseAPI, deleteCourseAPI } from '@/api/api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';

const tableData = ref()
const search = ref('')
const courseData = ref({
    courseName: '',
    description: '',
    belongDeptId: '',
    icon: '',
    teacherId: []
})
const visibleDialog = ref(false)
const uploadDisabled = ref(false)

//部门名
const deptOptions = ref([])
const dialogHeader = ref(1)

//题目分页
const paginationData = reactive({
    pageSize: 20,
    total: 0,
    pageNum: 1,
    background: false,
    disabled: false,
    small: '',
})

//定义一个响应式数组用来接收图片
const fileList = ref([])

//自定义函数用来覆盖原有的XHR行为（默认提交行为）
function httpRequest(option) {
    //将图片存到数组中
    fileList.value.push(option)
}

onMounted(() => {
    getCourseList()
    //获取部门信息
    findNodes()
})
const getCourseList = async () => {
    await getCourseListAPI().then(res => {
        console.log(res.data.data.list);
        tableData.value = res.data.data.list
    })
}
//当一页的数量改变
const handleSizeChange = (newPageSize) => {
    paginationData.pageSize = newPageSize
    getQueryBankListCourse(sessionStorage.getItem('courseId'))
}
//第几页
const handleCurrentChange = (newCurrentPage) => {
    paginationData.pageNum = newCurrentPage
    getQueryBankListCourse(sessionStorage.getItem('courseId'))
}
//获取所有部门信息
const findNodes = async () => {
    await findNodesAPI().then(res => {
        if (res.data.code) {
            deptOptions.value = getTreeData(res.data.data)
        }
    })
}
//获取树形部门
const getTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
        data[i].label = data[i].deptName
        data[i].value = data[i].id
        if (data[i].children == null || data[i].children.length < 1) {
            data[i].children = undefined     //避免children为空的时候，下一级显示为空白
        }
        else {
            getTreeData(data[i].children)
        }
    }
    return data
}
//搜索课程
const searchByTitel = () => { }
//新增课程按钮
const addCourseBtn = () => {
    courseData.value = {}
    visibleDialog.value = true
    dialogHeader.value = 1
}
//新增课程
const addCourse = async (courseData) => {
    const data = courseData
    if (data.belongDeptId) {
        if (data.belongDeptId.length > 1) {
            data.belongDeptId = Object.values(data.belongDeptId).pop()
        }
        data.belongDeptId = parseInt(data.belongDeptId)
    }
    data.icon = 'https://p.ananas.chaoxing.com/star3/240_130c/f23a4b313e1aa0a7a840ab81aabc918f.jpg'
    data.teacherId = [5]
    await addCourseAPI(data).then(res => {
        if (res.data.code == 200) {
            visibleDialog.value = false
            getCourseList()
            ElMessage.success('新增课程成功')
        }
    })
}
//更新课程按钮
const updateCourseBtn = async (data) => {
    dialogHeader.value = 2
    courseData.value = data
    visibleDialog.value = true
}
//更新课程
const updateCourse = async (courseData) => {
    const data = courseData
    delete data['createTime']
    delete data['creator']
    delete data['updateTime']
    data.teacherId = [5]
    console.log(data);
    await updateCourseAPI(data).then(res => {
        if (res.data.code == 200) {
            visibleDialog.value = false
            getCourseList()
            ElMessage.success('更新课程成功')
        }
    })
}


let courseId = ref([]);
//获取题目id
const selectCourseId = (data) => {
    data = JSON.parse(JSON.stringify(data))
    console.log(data);
    courseId.value = []
    for (let item of data) {
        courseId.value.push({
            ids: item.id
        })
    }
    console.log(courseId.value, 'courseId.value');
}
//批量删除题目
const deleteCourses = async (courseId) => {
    const id = ref([])
    for (let index = 0; index < courseId.length; index++) {
        const element = courseId[index].ids;
        id.value.push(element)
    }
    const ids = ref({ ids: id })
    await deleteCourseAPI(ids.value).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('删除成功')
            getCourseList()
        }

    })
}
//单独删除题目
const deleteCourse = (row) => {
    const courseId = ref([])
    courseId.value.push({
        ids: row.id
    })
    deleteCourses(courseId.value)
}


</script>

<style lang="less">
.el-dialog__header {
    margin: 0 !important;
    background-color: #f8f8f8 !important;
    border-bottom: 1px solid #eeeeee;
}

.el-dialog__footer {
    background-color: #f0f4f7 !important;
    padding: 10px !important;
    border-top: 1px solid #eeeeee;
}

.disabled .el-upload--picture-card {
    display: none;
}
</style>

<style lang="less" scoped>
.course-box {
    padding: 0;
    margin: 15px 0px 0 0;
    background-color: #fff;
    border-radius: 15px;

    .course-head {

        // border-bottom: 1px solid rgb(247, 247, 247);
        .head-title {
            font-size: 18px;
            font-weight: 550;
            color: grey;
            padding: 15px 10px 0px 10px;
        }

        .course {
            display: flex;
            justify-content: end;
            margin: 10px 5px 0px 5px;
            font-size: small;

            .option {
                display: flex;
                margin: 10px 10px 20px 10px;

                .option-word {
                    margin-top: 2px;
                    padding: 3px 7px;
                    font-size: 14px;
                }

                .select {
                    width: 130px;
                }

                .input {
                    width: 240px;

                }
            }

            .head-btn {
                margin: 10px 15px 0 5px;
            }
        }

    }

    .table {
        max-height: 66vh;
        min-height: 66vh;
        margin: auto;
        width: 1250px;
    }

    .foot {
        overflow: hidden;
        display: flex;
        justify-content: center;

        .question-foot {
            display: flex;
            justify-content: center;

            .pagination {
                margin-bottom: 10px;

            }

        }
    }

    .dialog {
        width: 100px;

        .dialog-form {
            margin: 0 auto;

            .dialog-input {
                width: 280px;
            }

        }


        .dialog-footer {
            display: flex;
            justify-content: end;
            margin-right: 20px;

            .dialog-btn {
                margin-top: 0;
                width: 80px;
            }
        }


    }


}
</style>